import {getInfo, login, logout} from '@/api/login'
import {removeUser, setUser} from '@/utils/auth'

const user = {
  state: {
    nickName: '',
    username: '',
    avatar: '',
    roles: [],
    user:{}
  },

  mutations: {
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_NICKNAME: (state, nickName) => {
      state.nickName = nickName
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      userInfo.username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const userInfo = response.data
          setUser(userInfo.nickName)
          commit('SET_USER', userInfo)
          commit('SET_NICKNAME', userInfo.nickName)
          commit('SET_USERNAME', userInfo.userName)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({commit}, userInfo) {
      // if (userInfo) {
      //   setUser(userInfo.nickName)
      //   commit('SET_NAME', userInfo.nickName)
      //   commit('SET_USERNAME', userInfo.userName)
      // }
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)

            const userInfo = data.user
            setUser(userInfo.nickName)
            commit('SET_USER', userInfo)
            commit('SET_NICKNAME', userInfo.nickName)
            commit('SET_USERNAME', userInfo.userName)
          } else {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject('该账号尚未分配角色!')
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_USER', {})
          commit('SET_NICKNAME', '')
          commit('SET_ROLES', [])
          commit('SET_USERNAME', '')
          removeUser()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_USER', {})
        commit('SET_NICKNAME', '')
        commit('SET_ROLES', [])
        commit('SET_USERNAME', '')
        removeUser()
        resolve()
      })
    }
  }
}

export default user
